const startTime = Date.now();
let startWorking = false;   // 标记是否开始工作
function sleep(time) {
return new Promise(resolve => {
    setTimeout(() => {
    resolve();
    }, time);
});
}
// 发送消息告诉background页面打开了
chrome.runtime.sendMessage({
    msg: 'pageOpened'
})

// 监听是否开始工作
chrome.runtime.onMessage.addListener((message,sender,response)=>{
    console.log('收到消息',message)
    switch (message.msg) {
        case "startWorking":
            startWorking = true;
            break;
    
        default:
            break;
    }
});

console.log('执行content.js', startTime)

// 获取quiz链接
const getItems = ()=>{
    const links = document.querySelectorAll('a.container-list-item');
    const quizzes = []
    links.forEach(item=>{
        const img = item.querySelector('img');
        quizzes.push({
            id: Math.random().toString(32).slice(2)+'_'+Date.now(),
            title: item.querySelector('p').innerText,
            url: item.href,
            thumb: img.src
        })
    })
    return quizzes
}

// 获取quiz结果
const getResult = ()=>{
    let pic = document.querySelector('.result-pic img')||document.querySelector('.result_img img')
    let desc = document.querySelector('.result_desc');

    if(pic){
        console.log('获取到图片',pic.src,pic.getAttribute('data-cfsrc'))
        if(pic.src.indexOf('loading')!==-1){  // 获取到的是打底图片
            location.reload()   // 重新加载
        }else{
            const obj = {
                pic: pic.src,            
            }
            if(desc){
                obj.desc = desc.innerText
            }
            return obj
        }
    }
    return null
}

let onload = false;  // 确保只执行一次onload事件
window.addEventListener('load',async e=>{    
    if(onload) return false;
    onload = true
    if(!startWorking) { // 如果onload事件执行的更早，sleep一下
        await sleep(2000);
    };
    if(document.querySelector('.container-list')){ // quiz列表页        
        const quizzes = getItems();  
        if(quizzes.length){
            chrome.runtime.sendMessage({msg:"quiz_info",data:quizzes})
            console.log('列表页，获取quiz链接',quizzes);
        }      

    }
    console.log('可以开工了吗',startWorking);
    if(!startWorking) return false;
    if(location.href.indexOf('/results/')!=-1){ // quiz结果页
        setTimeout(() => {  // 延迟获取内容
            const result = getResult();
            console.log('获取到results',result)
            if(result){
                chrome.runtime.sendMessage({
                    msg:"quiz_result",
                    data: result
                })
                // console.log('send message',result)
            }else{
                chrome.runtime.sendMessage({
                    msg:"quiz_error"
                })
            } 
        }, 2000);

    }else if(location.href.indexOf('/test/')!=-1){  // quiz二页   
        const descBox = document.querySelector('.question_desc')||document.querySelector('.question-main-desc');
        const input = document.querySelector('#loginForYourNameInput')
        const btn_play =  document.querySelector('#loginForYourNameSubmit')
        const opt_box = document.querySelector('.option-box');
        if(!input||!descBox){ // 找不到Input就报错
            chrome.runtime.sendMessage({
                msg:"quiz_error"
            })
            return ;
        }
        input.value = '~';   // 输入名字
        setTimeout(() => {
            console.log('模拟点击')
            btn_play.click(); // 模拟点击
            const opts = [];
            const labels = opt_box&&opt_box.querySelectorAll('table label')||[]
            labels.forEach((label,i)=>{
                const obj = {
                    id: i,
                    text: label.innerText
                }
                opts.push(obj)
            })
            
            const data = {
                desc: descBox.innerText
            }
            if(opts.length){
                var thumb_img = opt_box.querySelector('img');
                data.select = {
                    title: document.querySelector('.option-question>h3').textContent,
                    thumb: thumb_img?thumb_img.src:'',
                    options: opts
                };
                // 接收消息，判断点击哪个option
                chrome.runtime.onMessage.addListener((message,sender,response)=>{
                    console.log('收到message',message)
                    switch (message.msg) {
                        case 'quiz_options':
                            const quiz = message.data
                            const select_index = quiz.results?quiz.results.length:0

                            if(select_index<labels.length){

                                console.log('定时器点击label',labels[select_index],select_index)
                                labels[select_index].click(); // 模拟点击选项  
                                setTimeout(() => {  // 10秒后如果不跳转
                                    chrome.runtime.sendMessage({
                                        msg:"quiz_error"
                                    })
                                }, 10000);

                            }else{
                                chrome.runtime.sendMessage({    // 打开下一个quiz页
                                    msg:"next"
                                }) 
                            }
                            break;
                        default:
                            break;
                    }
                
                })
            }
            chrome.runtime.sendMessage({
                msg: "quiz_desc",
                data: data
            })
            console.log('send message',data)
        },2000);        

    }else{   // 页面不对
        chrome.runtime.sendMessage({
            msg:"quiz_error"
        })
    }

})


